package com.api.syh56.shengyunhui.service.impl;

import com.api.syh56.shengyunhui.common.Constants;
import com.api.syh56.shengyunhui.entity.*;
import com.api.syh56.shengyunhui.entity.adminEntity.AdminContact;
import com.api.syh56.shengyunhui.entity.adminEntity.AdminUser;
import com.api.syh56.shengyunhui.entity.common.ApiAreaDb;
import com.api.syh56.shengyunhui.entity.dto.WaybillUpdateDTO;
import com.api.syh56.shengyunhui.entity.vo.WAGParamVO;
import com.api.syh56.shengyunhui.entity.adminEntity.WaybillRoute;
import com.api.syh56.shengyunhui.entity.vo.WaybillDetailVO;
import com.api.syh56.shengyunhui.exception.BaseException;
import com.api.syh56.shengyunhui.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 运单管理
 */
@Service
public class AdminWayBillServiceImpl implements AdminWayBillService {
    @Autowired
    private WayBillService wayBillService;

    @Autowired
    private ApiAreaDbService apiAreaDbService;

    @Autowired
    private TmpAddressService tmpAddressService;

    @Autowired
    private RoutesService routesService;

    @Autowired
    private UserService userService;

    @Autowired
    private QuoteService quoteService;

    @Autowired
    private AdminContactService adminContactService;

    @Autowired
    private AdminSupService adminSupService;

    @Autowired
    private WaybillRouteService waybillRouteService;

    @Autowired
    private GoodsService goodsService;

    @Override
    public Page<WAGParamVO> select(Integer pageNum, Integer pageSize, String waybillNum, String waybillStatus, String oriCity, String desCity, String goodsName, String shipCompany, String driverCompany) {
        Page<Waybill> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Waybill> wrapper = new QueryWrapper<>();
        if (!waybillNum.isEmpty()) {
            wrapper.lambda().eq(Waybill::getWaybillNumber,waybillNum);//运单编号
        }
        if (!waybillStatus.isEmpty()) {
            short status = Short.parseShort(waybillStatus);
            wrapper.lambda().eq(Waybill::getWaybillStatus,status);//运单状态
        }
        if (!oriCity.isEmpty()){
            ApiAreaDb apiAreaDb = apiAreaDbService.selectByCityN(oriCity);
            wrapper.lambda().eq(Waybill::getOriAdCode,apiAreaDb.getAdCode());
        }
        if (!desCity.isEmpty()){
            ApiAreaDb apiAreaDb = apiAreaDbService.selectByCityN(desCity);
            wrapper.lambda().eq(Waybill::getDstAdCode,apiAreaDb.getAdCode());
        }
        if (!goodsName.isEmpty()){
            QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
            goodsQueryWrapper.lambda().eq(Goods::getGoodsName,goodsName);
            List<Goods> list = goodsService.list(goodsQueryWrapper);
            ArrayList<Long> goodsIds = new ArrayList<>();
            for (Goods goods : list) {
                goodsIds.add(goods.getId());
            }
            wrapper.lambda().in(Waybill::getGoodsId,goodsIds);
        }
        if (!shipCompany.isEmpty()) {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.lambda().like(User::getCompany,shipCompany);
            List<User> users = userService.list(userQueryWrapper);
            ArrayList<Long> uid = new ArrayList<>();
            for (User user : users){
                uid.add(user.getId());
            }
            wrapper.lambda().in(Waybill::getShiperId,uid);
        }
        if (!driverCompany.isEmpty()) {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.lambda().like(User::getCompany,driverCompany);
            List<User> users = userService.list(userQueryWrapper);
            ArrayList<Long> uid = new ArrayList<>();
            for (User user : users){
                uid.add(user.getId());
            }
            wrapper.lambda().in(Waybill::getDriverId,uid);
        }
        wrapper.lambda().orderByDesc(Waybill::getCreationTime);
        Page<Waybill> waybillPage = wayBillService.page(page, wrapper);
        Page<WAGParamVO> wagParamVOPage = wayBillService.waybillPageToWAGParamVOPage(waybillPage);
        return wagParamVOPage;
    }

    /**
     * 删除运单
     * @param id
     */
    @Override
    public void delete(Long id) {
        wayBillService.deleteWaybill(id);
    }

    /**
     * 修改运单状态
     * @param waybillUpdateDTO
     */
    @Override
    public void updateById(WaybillUpdateDTO waybillUpdateDTO) {
        Waybill waybill = wayBillService.selectById(waybillUpdateDTO.getWaybillId());
        if (waybill == null){
            throw new BaseException("id不存在");
        }
        waybill.setWaybillStatus(waybillUpdateDTO.getState());
        wayBillService.updateById(waybill);
    }

    @Override
    public List<WaybillRoute> getRouteByWid(Long wid) {
        Waybill waybill = wayBillService.getById(wid);
        Long oriAdCode = waybill.getOriAdCode();
        Long dstAdCode = waybill.getDstAdCode();
        QueryWrapper<Routes> routesQueryWrapper = new QueryWrapper<>();
        routesQueryWrapper.lambda()
                .eq(Routes::getOriAdCode,oriAdCode)
                .eq(Routes::getDstAdCode,dstAdCode);
        List<Routes> list = routesService.list(routesQueryWrapper);
        List<WaybillRoute> waybillRoutes = new ArrayList<>();
        for(Routes routes : list) {
            Long uid = routes.getUid();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.lambda()
                    .eq(User::getId,uid)
                    .eq(User::getAuthStatus,Constants.Role.DRIVER);
            User user = userService.getOne(userQueryWrapper);
            if (user != null) {
                WaybillRoute waybillRoute = new WaybillRoute();
                BeanUtils.copyProperties(user, waybillRoute);
                waybillRoute.setUid(uid);
//            wrvo.setCompany(user.getCompany());
//            wrvo.setTelephone(user.getTelephone());
                QueryWrapper<Quote> wrapper = new QueryWrapper<>();
                wrapper.lambda()
                        .eq(Quote::getWaybillId,waybill.getId())
                        .eq(Quote::getDriverId,uid);
                Quote quote = quoteService.getOne(wrapper);
                if (Objects.isNull(quote)) {
                    waybillRoute.setQuoteStatus(Constants.WaybillQuote.UNQUOTE);
                }else {
                    waybillRoute.setQuoteStatus(Constants.WaybillQuote.IS_QUOTE);
                }
                QueryWrapper<AdminContact> contactWrapper = new QueryWrapper<>();
                contactWrapper.lambda().eq(AdminContact::getWid,wid);
                List<AdminContact> contacts = adminContactService.list(contactWrapper);
                if (!contacts.isEmpty()) {
                    Long sid = contacts.get(0).getSid();
                    AdminUser adminUser = adminSupService.getById(sid);
                    waybillRoute.setContactStatus(Constants.CONTACT.IS_CONTACT);
                    waybillRoute.setAdminUsername(adminUser.getUsername());
                }else {
                    waybillRoute.setContactStatus(Constants.CONTACT.UN_CONTACT);
                    waybillRoute.setAdminUsername(null);
                }
                waybillRoute.setWid(wid);
                waybillRoutes.add(waybillRoute);
            }
        }
        return waybillRoutes;
    }

    @Override
    public List<WaybillRoute> getRouteByWidN(Long wid) {
        QueryWrapper<WaybillRoute> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(WaybillRoute::getWid,wid);
        List<WaybillRoute> waybillRoutes = waybillRouteService.list(wrapper);
        return waybillRoutes;
    }


    @Override
    public Page<WaybillDetailVO> getWaybill(Integer pageNum, Integer pageSize) {
        Page<Waybill> waybillPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Waybill> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(Waybill::getWaybillStatus,Constants.WaybillStatus.AWAIT_QUOTE)
                .orderByDesc(Waybill::getCreationTime);
        Page<Waybill> page = wayBillService.page(waybillPage, wrapper);
        Page<WaybillDetailVO> waybillDetailVOPage = new Page<>();
        waybillDetailVOPage.setTotal(page.getTotal());
        waybillDetailVOPage.setSize(page.getSize());
        waybillDetailVOPage.setCurrent(page.getCurrent());
        List<Waybill> records = page.getRecords();
        ArrayList<WaybillDetailVO> waybillDetailVOS = new ArrayList<>();
        for (Waybill waybill : records){
            WaybillDetailVO waybillDetailVO = new WaybillDetailVO();
            Long shipAddressId = waybill.getShipAddressId();
            Long receiveAddressId = waybill.getReceiveAddressId();
            TmpAddress ship = tmpAddressService.getById(shipAddressId);
            TmpAddress receive = tmpAddressService.getById(receiveAddressId);
            waybillDetailVO.setOriCity(ship.getCity());
            waybillDetailVO.setDstCity(receive.getCity());
            Long oriAdCode = waybill.getOriAdCode();
//            ApiAreaDb oriCity = apiAreaDbService.selectByAdCode(String.valueOf(oriAdCode));
            Long dstAdCode = waybill.getDstAdCode();
//            ApiAreaDb dstCity = apiAreaDbService.selectByAdCode(String.valueOf(dstAdCode));
            System.out.println(oriAdCode+":::::"+dstAdCode);
            BeanUtils.copyProperties(waybill,waybillDetailVO);
//            waybillDetailVO.setOriCity(oriCity.getName());
//            waybillDetailVO.setDstCity(dstCity.getName());
            QueryWrapper<Routes> routesQueryWrapper = new QueryWrapper<>();
            routesQueryWrapper.lambda()
                    .eq(Routes::getOriAdCode,oriAdCode)
                    .eq(Routes::getDstAdCode,dstAdCode);
            List<Routes> list = routesService.list(routesQueryWrapper);
            System.out.println("RouteList:"+list);
            List<User> users = new ArrayList<>();
            for(Routes routes : list) {
                Long uid = routes.getUid();
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.lambda()
                        .eq(User::getId,uid)
                        .eq(User::getAuthStatus,Constants.Role.DRIVER);
                User user = userService.getOne(userQueryWrapper);
                if (user != null) {
                    users.add(user);
                }
            }
            System.out.println("+++++------------------------------------------------------+++++++++++"+users.size());
            waybillDetailVO.setRouteNum(users.size());
            waybillDetailVOS.add(waybillDetailVO);
        }
        Page<WaybillDetailVO> detailVOPage = waybillDetailVOPage.setRecords(waybillDetailVOS);
        return detailVOPage;
    }
}
